package GUI;

import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RunnerThread extends Thread {
	private GUI m_gui;
	final int m_frameDelay = 20; // milliseconds.
	public volatile boolean m_abort = false;
	public volatile boolean m_realtime = false;
	public volatile boolean m_step = false;
	public volatile Semaphore s;
	RunnerThread(GUI gui) {
		m_gui = gui;
                s = new Semaphore(1);
	}

	public void run() {
                DrawThread dt = null;
                UpdateThread updater = null;
		while (!m_abort) {
			synchronized (this) {
				while (!m_realtime && !m_step) {
					try {
						wait(100);
						if (m_abort) return;
					} catch (InterruptedException e) {
				    }
				}
			}
			
			m_step = false;
			
			long startTime = System.nanoTime();
                        updater = new UpdateThread(m_gui.controller);
			updater.start();
                        //m_gui.controller.update();
			long endTime = System.nanoTime();
                        dt = new DrawThread(m_gui);
                        dt.start();
			//m_gui.needsRedraw();
                        
                        System.out.println("Desenhou");
			if (m_gui.controller.isGameOver()) return;
			                        if(dt != null){
                        }
			if (m_realtime) {
				// Delay until next move.
				long timeTaken = (endTime - startTime) / 1000000;
				if (false) {
					try {
						sleep(m_frameDelay - timeTaken);
					} catch (InterruptedException e) {
						// Ignore.
					}
				}else{
                                    System.out.println("Nao Juntou");
                                try {
                                    dt.join();
                                    updater.join();
                                    System.out.println("Juntou");
                                } catch (InterruptedException ex) {
                                    Logger.getLogger(RunnerThread.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                }
			}
                        
		}
	}
}